import torch
import torchvision
from torch import nn
from torch.utils.data import DataLoader
from torch.utils.tensorboard import SummaryWriter

from model import Net  # 确保model.py中有Net类的定义

# 准备训练数据集
train_dataset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True,
                                             transform=torchvision.transforms.ToTensor())
# 测试数据集
test_dataset = torchvision.datasets.CIFAR10(root='./data', train=False, download=True,
                                            transform=torchvision.transforms.ToTensor())

# 输出训练数据集的长度
train_data_size = len(train_dataset)
test_data_size = len(test_dataset)
print(f"训练数据集的长度为：{train_data_size}\n测试数据集的长度为：{test_data_size}")

# 利用DataLoader加载数据
test_loader = DataLoader(test_dataset, batch_size=64)
train_loader = DataLoader(train_dataset, batch_size=64)

# 创建网络模型
net = Net()

# 损失函数
loss_fn = nn.CrossEntropyLoss()
# 优化器
learning_rate = 0.01
optimizer = torch.optim.SGD(net.parameters(), lr=learning_rate)

# 设置训练网络的一些参数
# 记录训练的次数
total_train_step = 0
# 记录测试的次数
total_test_step = 0
# 训练的轮数
epoch = 10

# 添加tensorboard
writer = SummaryWriter("logs")

for i in range(epoch):
    print(f"--------第 {i + 1} 轮训练开始--------")
    # 训练步骤开始
    net.train()  # 设置为训练模式
    for data in train_loader:
        inputs, targets = data
        outputs = net(inputs)
        loss = loss_fn(outputs, targets)

        # 优化器优化模型
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        total_train_step = total_train_step + 1
        if total_train_step % 100 == 0:
            print(f"训练次数：{total_train_step}\tLoss: {loss.item()}")
            writer.add_scalar("train_loss", loss.item(), total_train_step)

    # 测试步骤开始
    print("---------开始测试---------")
    net.eval()  # 设置为评估模式
    test_total_loss = 0
    total_accuracy = 0

    with torch.no_grad():
        for data in test_loader:
            inputs, targets = data
            outputs = net(inputs)
            loss = loss_fn(outputs, targets)
            test_total_loss += loss.item()
            accuracy = (outputs.argmax(1) == targets).sum().item()
            total_accuracy += accuracy

    avg_test_loss = test_total_loss / len(test_loader)
    test_accuracy = total_accuracy / test_data_size
    print(f"测试集Loss: {avg_test_loss:.4f}, 准确率: {test_accuracy:.4f}")
    writer.add_scalar("test_loss", avg_test_loss, total_test_step)
    writer.add_scalar("test_accuracy", test_accuracy, total_test_step)
    total_test_step += 1

    # # 修改后的模型保存方式：只保存state_dict
    # torch.save({
    #     'epoch': i,
    #     'model_state_dict': net.state_dict(),
    #     'optimizer_state_dict': optimizer.state_dict(),
    #     'loss': avg_test_loss,
    # }, f"net_epoch_{i}.pth")

# 保存最后一轮模型（单独保存一个文件）
final_model_path = "net_final.pth"
torch.save(net.state_dict(), final_model_path)
print(f"最终模型已保存到: {final_model_path}")

writer.close()